<?

require_once("mysql.php");
require_once("captcha.php");
require_once("reference.php");
require_once("location.php");
require_once("session.php");
require_once("utilities.php");

function find_or_create_local_item_image($im) {

    /*
     * Special image
     */
    if (starts_with($im, "images/")) {
        if (trim($im) == "images/null.png" || trim($im) == "images/no.png") {
            return "images/n.png";
        }
    }

    if (starts_with($im, "pic/")) return $im;

    $r = MYSQL_Q("SELECT * FROM photo WHERE original='".$im."'");
    $c = mysql_num_rows($r);

    if ($c == 0) {

        do {
            $absolute = "../pic/".rstring(12);
        } while (@file_exists($absolute));

        $image = @file_get_contents($im);

        if (!$image) {
            echo '["Image link for <strong>'.$_POST['item'].'</strong> broken"]'; die();
        }

        if (!@file_put_contents($absolute, $image)) {
            echo '["Error: 0x0004"]'; die();
        }

        $relative = substr($absolute, 3);

        MYSQL_Q("INSERT INTO photo VALUES ('".$relative."', '".$im."', 1, 1)");

        return $relative;

    } else {

        $row = mysql_fetch_assoc($r);
        MYSQL_Q("UPDATE photo SET count=count+1 WHERE original='".$im."'");
        return $row['path'];

    }
  
}


function create_deal($i, $s) {  

    if ($i['online_seller'] == true) {
        $loc = find_or_create_location($i['location'], $i['latitude'], $i['longitude'], 2);
    }

    $p = find_or_create_local_item_image($i['item_image']);
    $S = find_or_create_session(); // should always be found!
 
    $q = "INSERT INTO deal (user, session, seller, item, value, time, location, photo, link, description, category, visibility) ".
         "VALUES (%s, %d, %s, '%s', %s, UNIX_TIMESTAMP(NOW()), %s, %s, %s, %s, %s, %s)";

    $q = sprintf($q, 
                 @isset($_SESSION['userid']) ? $_SESSION['userid'] : 'NULL',
                 $S,
                 $s['id'],
                 $i['item'],
                 $i['value'],
                 // TIME
                 $i['online_seller'] ? (string)$loc: 'NULL',
                 empty($p) ? 'NULL'                : "'".$p."'",
                 empty($i['link']) ? 'NULL'        : "'".$i['link']."'",
                 empty($i['description']) ? 'NULL' : "'".$i['description']."'",
                 empty($i['category']) ? 'NULL'    : "'".$i['category']."'",
                 empty($i['visibility']) ? '0'     : "'".$i['visibility']."'"
                 );   

    $r = @MYSQL_Q($q);

    if (!$r) {
        unlink("../".$p);
        //echo '["Error: 0x0006"]'; 
        die();
    }

    // now update the refcount for the seller if we successfully created the deal
    MYSQL_Q('UPDATE seller SET count='.($s['count']+1).' WHERE id='.$s['id']);
 
}

 
?>